<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreDepartmentRequest;
use App\Http\Requests\UpdateDepartmentRequest;
use App\Http\Resources\DepartmentResource;
use App\Http\Traits\CheckPermission;
use App\Http\Traits\LogOperation;
use App\Models\Department;
use App\Models\Permission;
use App\Services\DepartmentService;
use Illuminate\Http\Request;

class DepartmentController extends Controller
{
    use CheckPermission, LogOperation;

    protected $departmentService;
    protected $resource = 'departments';

    public function __construct(DepartmentService $departmentService)
    {
        $this->departmentService = $departmentService;
        $this->middleware('auth.api');
    }

    public function index(Request $request)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);

        if ($request->has('tree')) {
            $conditions = [];
            if ($request->has('status')) {
                $conditions['status'] = $request->status;
            }
            $departments = Department::tree(0, $conditions);
            // 使用Resource格式化树形数据，包括时间字段
            // tree方法返回的是Collection，且已设置children关系，Resource会自动处理
            $formattedDepartments = DepartmentResource::collection($departments)->resolve(request());
            return $this->success($formattedDepartments, '获取成功');
        }

        $filters = $request->only(['name', 'status']);
        $query = $this->departmentService->buildQuery($filters);
        $departments = $query->paginate($this->getPageSize($request));

        // 使用Resource格式化分页数据，包括时间字段
        $departments->setCollection(
            $departments->getCollection()->map(function ($department) {
                return (new DepartmentResource($department))->resolve(request());
            })
        );

        return $this->success($departments, '获取成功');
    }

    public function store(StoreDepartmentRequest $request)
    {
        // 检查新增权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_CREATE);

        $department = $this->departmentService->create($request->validated());
        
        // 记录创建操作
        $this->logCreate($this->resource, $department, "创建部门: {$department->name}", $request);
        
        return $this->success(new DepartmentResource($department), '创建成功');
    }

    public function show($id)
    {
        // 检查查看权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_VIEW);

        $department = Department::with('parent')->findOrFail($id);
        return $this->success(new DepartmentResource($department), '获取成功');
    }

    public function update(UpdateDepartmentRequest $request, $id)
    {
        // 检查编辑权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_UPDATE);

        $department = Department::findOrFail($id);
        // 保存更新前的数据
        $originalData = $department->toArray();
        
        $department = $this->departmentService->update($department, $request->validated());
        
        // 记录更新操作
        $this->logUpdate($this->resource, $department, $originalData, "更新部门: {$department->name}", $request);
        
        return $this->success(new DepartmentResource($department), '更新成功');
    }

    public function destroy($id)
    {
        // 检查删除权限
        $this->authorizeButtonPermission($this->resource, Permission::ACTION_DELETE);

        $department = Department::findOrFail($id);
        
        try {
            // 记录删除操作（在删除前记录）
            $this->logDelete($this->resource, $department, "删除部门: {$department->name}", request());
            
            $this->departmentService->delete($department);
            return $this->success(null, '删除成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 400);
        }
    }
}

